import os
import subprocess

import command
import constants


def modify_env_config():
    result = command.exe_command_with_powershell(constants.WIN_GET_EXECUTIONPOLICY)
    if result.stdout == "Restricted":
        command.exe_command_with_powershell(constants.WIN_SET_EXECUTIONPOLICY)
    # 获取 PowerShell 配置文件路径
    ps_profile_command = "$PROFILE"
    ps_profile = subprocess.run(["powershell", "-Command", ps_profile_command], capture_output=True,
                                text=True).stdout.strip()

    # 检查配置文件是否存在
    if not os.path.exists(ps_profile):
        # 创建配置文件路径
        os.makedirs(os.path.dirname(ps_profile), exist_ok=True)
        # 创建配置文件
        with open(ps_profile, 'w'):
            pass

    # Chocolatey profile 模块路径
    choco_profile_path = constants.WIN_IMPORT_MODULE

    # 检查配置文件中是否已包含导入命令
    with open(ps_profile, 'r') as r_file:
        content = r_file.read()

    if choco_profile_path not in content:
        # 追加导入 Chocolatey profile 模块的命令到配置文件
        with open(ps_profile, 'a') as file:
            file.write(f"{choco_profile_path}\n")

    print(f"PowerShell 配置文件已更新: {ps_profile}")
